package com.qf.dao.impl;

import com.qf.dao.ProductDao;
import com.qf.pojo.Product;
import com.qf.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class ProductDaoImpl implements ProductDao {
    @Override
    public List<Product> selectProduct() throws SQLException {
        QueryRunner qr= new QueryRunner(JdbcUtils.getDataSource());
        String sql = "SELECT * FROM product ORDER BY pdate DESC LIMIT 9";
        List<Product> list = qr.query(sql, new BeanListHandler<Product>(Product.class));
        return list;

    }

    @Override
    public List<Product> selectHotProduct() throws SQLException {
        QueryRunner qr= new QueryRunner(JdbcUtils.getDataSource());
        String sql = "SELECT * FROM product WHERE is_hot = 1;";
        List<Product> list = qr.query(sql, new BeanListHandler<Product>(Product.class));
        return list;

    }

    @Override
    public Product selectProductById(String pid) throws SQLException {
        //获取数据
        QueryRunner qr =new QueryRunner(JdbcUtils.getDataSource());
        //准备sql
        String sql = "select * from product where pid = ?";
        //执行sql语句
        Product product = qr.query(sql, new BeanHandler<Product>(Product.class), pid);
        return product;
    }

    @Override
    public List<Product> selectProductByPage( int currentPage, int pageSize, String cid) throws SQLException {
        //获取数据
        QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
        //准备sql
        String sql = "select * from product  where cid = ? limit ?,?";
        List<Product> list = qr.query(sql, new BeanListHandler<Product>(Product.class), cid,(currentPage-1)*pageSize,pageSize);
        return list;
    }

    @Override
    public int findTotalCountByCid(String cid) throws SQLException {
        //获取总记录数
        QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
        //准备sql
        String sql = "SELECT COUNT(*) FROM product WHERE cid = ?";
        Object obj = qr.query(sql, new ScalarHandler<>(), cid);
        //类型转换
        String s = String.valueOf(obj);
        int totalCount = Integer.parseInt(s);

        return totalCount;
    }
}
